﻿using System.Collections.Specialized;
using IrelandAlt.ORNetTwitt.Resources;
using OpenRasta.Web;

namespace IrelandAlt.ORNetTwitt.Handlers
{
    public class AuthenticationUiHandler
    {
        private IUserSecurity UserSecurityContext;

        public AuthenticationUiHandler(ICommunicationContext communicationContext)
        {
            // TODO: checkout OpenRasta.Security.IAuthenticationProvider
            UserSecurityContext = HandlerHelper.GetUserSecurityContext(communicationContext);
        }

        public OperationResult Post(UserUiResource loginUser)
        {
            // if ok redirect to home
            // else to loginFailed with message
            if (AuthenticateUser(loginUser))
            {
                UserUiResource authUser = new UserUiResource(UserSecurityContext) { UserName = loginUser.UserName };
                
                authUser.MakeUserAuthenticated();

                authUser.UserId = 100;

                var vals = new NameValueCollection { { "id", authUser.UserId.ToString() } };

                return new OperationResult.SeeOther { RedirectLocation = typeof(UserHomeUiResource).CreateUri(vals) };
            }

            return new OperationResult.SeeOther { RedirectLocation = typeof(HomeUiResource).CreateUri() };
        }

        private static bool AuthenticateUser(UserUiResource user)
        {
            //test for user in db, if password matches
            // set communicationContext.User = user
            // if not return false
           
            return true;
        }
    }
}
